package com.gylang.crawler.selenium;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;

/**
 * @author gylang
 * data 2021/5/29
 */
public class SeleniumProcessor implements PageProcessor {
    private Site site;

    @Override
    public void process(Page page) {
        List<String> titles = page.getHtml().xpath("//a[@class='link title']/text()").all();
        page.putField("title", titles);

    }

    @Override
    public Site getSite() {
        if (site == null) {
            site = Site.me().setDomain("https://www.toutiao.com")
                    .setSleepTime(1000);
        }
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new SeleniumProcessor())
                .addUrl("https://www.toutiao.com/c/user/50502347096/#mid=50502347096")
                .thread(5)
                .addPipeline(new ConsolePipeline())
                /*
                 * 为 SeleniumDownloader 设置休眠时间：
                 *     当动态加载页面时，可能还存在部分数据没有加载完毕，为它设置休眠时间后，可保证有足够的时间，加载完
                 */
                .setDownloader(new SeleniumDownloader(SeleniumProcessor.class.getResource("/chromedriver.exe").getPath()).setSleepTime(1000))
                .run();
    }
}

